var config = require("../config.js");
var app = getApp();
//login---------------------------------------------------------
function getOpenId(cb){
    wx.login({
      success: function(res){
        if(res.code){
          var url=config.openIdUrl+'?appid='+config.appid+'&secret='+config.secret+'&js_code='+res.code+'&grant_type=authorization_code';
          wx.request({
            url: url,
            data: {},
            method: 'GET',
            success: function(res){
              typeof cb == "function" && cb(res.data.openid);
            },
            fail:function(){
              console.log("获取用户微信号失败");
            }
          })
        }
      }
    })
}
function login(){
      var app = getApp();
      getOpenId(function(res){
        if(res){
          wx.request({
          url: config.loginUrl,
          data: {weChat:res},
          method: 'POST', 
          success: function(res){
            console.log(res.data.code)
            if(res.data.code == '0'){
              //用户不存在
              wx.redirectTo({
                url: '/pages/identifyDoc/register/register',
              })
            }else if(res.data.code == '1'){
              app.setNumber(res.data.data[0].number);
              app.setNickName(res.data.data[0].nickname);
              console.log( app.globalData)
              wx.switchTab({
                url: '../../searchBook/index',
              })

            }else{
              console.log('code读取错误，code='+code);
            }
          },
          fail: function() {
            console.log("服务器故障");
      }
  })
        }
      })
     
}

//searchBook-----------------------------------------------------
function searchBook(para){
  if(para&&para!=''){
    wx.request({
      url: config.searchBookUrl,
      data: {name:para},
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function(res){
        if(res.code == '0'){

        }else if(res.code == '1'){

        }else{
        }
      },
      fail: function() {
        console.log('服务器出现问题')
      }
    })
  }
}

//config---------------------------------------------------------
module.exports = {
  login: login,
  getOpenId:getOpenId,
  searchBook:searchBook,
}